<template>
  <view class="orders-container">
    <!-- 顶部标题栏 -->
    <view class="page-header">
      <view class="header-title">我的订单</view>
    </view>
    
    <!-- 标签栏（可横向滚动） -->
    <scroll-view 
      class="tabs-scroll" 
      scroll-x 
      show-scrollbar="false"
      :scroll-with-animation="true"
    >
      <view class="tabs">
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'ongoing' }"
          @click="switchTab('ongoing')"
        >
          进行中
          <view class="tab-badge" v-if="tabCounts.ongoing > 0">
            {{ tabCounts.ongoing }}
          </view>
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'unpaid' }"
          @click="switchTab('unpaid')"
        >
          未支付
          <view class="tab-badge" v-if="tabCounts.unpaid > 0">
            {{ tabCounts.unpaid }}
          </view>
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'pendingComment' }"
          @click="switchTab('pendingComment')"
        >
          待评论
          <view class="tab-badge" v-if="tabCounts.pendingComment > 0">
            {{ tabCounts.pendingComment }}
          </view>
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'history' }"
          @click="switchTab('history')"
        >
          历史订单
          <view class="tab-badge" v-if="tabCounts.history > 0">
            {{ tabCounts.history }}
          </view>
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'cancelled' }"
          @click="switchTab('cancelled')"
        >
          已取消
          <view class="tab-badge" v-if="tabCounts.cancelled > 0">
            {{ tabCounts.cancelled }}
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 工单列表 -->
    <view class="order-list">
      <!-- 工单项 -->
      <view 
        class="order-item" 
        v-for="order in filteredOrders" 
        :key="order.id"
        @click="viewDetail(order.id)"
      >
        <!-- 工单头部 -->
        <view class="order-header">
          <view class="order-number">
            <text class="number-label">订单编号：</text>
            <text>{{ order.id }}</text>
          </view>
          <view 
            class="order-status" 
            :class="`status-${order.status}`"
          >
            {{ getStatusText(order.status) }}
          </view>
        </view>
        
        <!-- 工单详情 -->
        <view class="order-details">
          <view class="detail-row">
            <text class="detail-icon">🔧</text>
            <text class="detail-label">类型</text>
            <text class="detail-value">{{ order.type }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-icon">📍</text>
            <text class="detail-label">地址</text>
            <text class="detail-value">{{ order.address }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-icon">⏰</text>
            <text class="detail-label">时间</text>
            <text class="detail-value">{{ order.time }}</text>
          </view>
          <view class="detail-row price-row">
            <text class="detail-icon">💴</text>
            <text class="detail-label">报酬</text>
            <text class="detail-value" v-if="order.status === 2">¥{{ (parseFloat(order.price || 0) + parseFloat(order.servicePay || 0)).toFixed(2) }}</text>
            <text class="detail-value" v-else-if="order.status === 0 || order.status === 1">等待员工结算</text>
            <text class="detail-value" v-else>¥{{ order.price?.toFixed(2) }}</text>
          </view>
        </view>
        
        <!-- 操作按钮 -->
        <view class="order-actions">
          <button class="detail-btn" @click.stop="viewDetail(order.id)">
            查看详情
          </button>
          <button 
            class="comment-btn" 
            @click.stop="goToComment(order.id)"
            v-if="activeTab === 'pendingComment'"
          >
            去评论
          </button>
          <button 
            class="pay-btn" 
            @click.stop="goToPay(order.id)"
            v-if="activeTab === 'unpaid'"
          >
            去支付
          </button>
          <button 
            class="cancel-btn" 
            @click.stop="cancelOrder(order.id)"
            v-if="activeTab === 'ongoing'"
          >
            取消订单
          </button>
          <button 
            class="return-btn" 
            @click.stop="returnToHall(order.id)"
            v-if="order.status !== 'completed' && activeTab !== 'ongoing' && activeTab !== 'pendingComment' && activeTab !== 'history' && activeTab !== 'unpaid' && activeTab !== 'cancelled'"
          >
            退回大厅
          </button>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredOrders.length === 0">
        <view class="empty-icon">📋</view>
        <view class="empty-text">暂无相关订单</view>
        <view class="empty-subtext">
          {{ getEmptySubtext() }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getWorkOrderListAPI, getWorkOrderListByCustomerIdAPI, cancelWorkOrderAPI } from '@/api/order.js'

// 核心修复1：安全获取路由实例，添加兜底逻辑
const router = useRouter?.() || {
  push: (options) => {
    // 路由实例不存在时，使用uni.navigateTo兜底
    const url = typeof options === 'string' 
      ? options 
      : `${options.path}?${new URLSearchParams(options.query || {}).toString()}`
    uni.navigateTo({ url })
  }
}

// 工单数据
const orders = ref([])

// 加载状态
const loading = ref(false)

// 当前激活的标签
const activeTab = ref('ongoing')

// 获取工单列表
const fetchOrders = async () => {
  loading.value = true
  uni.showLoading({ title: '加载中' })
  
  try {
    // 获取本地存储的用户信息
    const userInfo = uni.getStorageSync('userInfo');
    let res = [];
    
    // 如果用户已登录且有ID，则获取该用户的订单列表
    if (userInfo && userInfo.id) {
      res = await getWorkOrderListByCustomerIdAPI(userInfo.id);
    } else {
      // 否则获取所有订单列表
      res = await getWorkOrderListAPI();
    }
    
    // 处理接口返回的数据，添加tab字段
    if (res && Array.isArray(res)) {
      orders.value = res.map(item => {
        // 根据订单状态确定tab（按新的分类规则）
        // 进行中订单：status为0（待分配）和1（处理中）
        // 未支付订单：pay_status=0 且 status!=3
        // 待评论订单：status为2（已完成）
        // 历史订单：status为4且pay_status=1（已完成且已支付）或status为1（根据新要求）
        // 已取消订单：status为3
        let tab = 'history'
        if (item.status === 0 || item.status === 1) {
          tab = 'ongoing'
        } else if (item.payStatus === 0 && item.status === 2) {
          tab = 'unpaid'
        } else if (item.status === 2 && item.payStatus === 1) {
          tab = 'pendingComment'
        } else if ((item.payStatus === 1 && item.status === 4) || item.status === 1) {
          tab = 'history'
        } else if (item.status === 3) {
          tab = 'cancelled'
        }
        
        return {
          ...item,
          tab,
          // 确保必要的字段存在
          id: item.id || '',
          type: item.type || item.title || '', // 根据映射规范，title对应type
          address: item.address || '',
          time: item.createTime || item.updateTime || '', // 使用createTime或updateTime
          // 确保数值字段正确，映射数据库字段
          price: item.pay !== undefined ? item.pay : (item.price || 0),
          servicePay: item.service_pay !== undefined ? item.service_pay : (item.servicePay || 0),
          status: item.status !== undefined ? item.status : 0, // 默认为0（待分配）
          payStatus: item.payStatus !== undefined ? item.payStatus : 0 // 默认为0（未支付）
        }
      }).sort((a, b) => {
        // 按时间倒序排列，最新的在前面
        const timeA = a.time || '';
        const timeB = b.time || '';
        return timeB.localeCompare(timeA);
      });
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    uni.showToast({
      title: '获取订单失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    uni.hideLoading()
  }
}

// 计算每个标签的工单数量
const tabCounts = computed(() => {
  return {
    ongoing: orders.value.filter(order => order.tab === 'ongoing').length,
    unpaid: orders.value.filter(order => order.tab === 'unpaid').length,
    pendingComment: orders.value.filter(order => order.tab === 'pendingComment').length,
    history: orders.value.filter(order => order.tab === 'history').length,
    cancelled: orders.value.filter(order => order.tab === 'cancelled').length
  }
})

// 根据当前标签筛选工单
const filteredOrders = computed(() => {
  return orders.value.filter(order => order.tab === activeTab.value)
})

// 切换标签
const switchTab = (tabName) => {
  activeTab.value = tabName
  // 滚动到顶部
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 300
  })
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    0: '待分配',
    1: '处理中',
    2: '已完成',
    3: '已取消',
    4: '已评价'
  }
  return map[status] || '未知状态'
}

// 获取空状态提示文本
const getEmptySubtext = () => {
  if (activeTab.value === 'history') {
    return '您暂无历史订单'
  } else if (activeTab.value === 'pendingComment') {
    return '您暂无待评论订单'
  } else if (activeTab.value === 'unpaid') {
    return '您暂无未支付订单'
  } else if (activeTab.value === 'cancelled') {
    return '您暂无已取消订单'
  } else if (activeTab.value === 'ongoing') {
    return '暂无进行中的订单'
  } else {
    return '暂无相关订单'
  }
}

// 去评论
const goToComment = (orderId) => {
  if (!orderId) {
    uni.showToast({ title: '订单ID无效', icon: 'none' })
    return
  }
  
  try {
    // 直接使用uni.navigateTo确保参数正确传递
    uni.navigateTo({
      url: `/pages/order-evaluation/order-evaluation?id=${orderId}`,
      fail: (err) => {
        console.error('无法打开评论页:', err)
        uni.showToast({ title: '无法打开评论页', icon: 'none' })
      }
    })
  } catch (e) {
    console.error('路由跳转失败:', e)
    uni.showToast({ title: '无法打开评论页', icon: 'none' })
  }
}

// 核心修复2：查看详情 - 添加错误捕获和参数校验
const viewDetail = (orderId) => {
  if (!orderId) {
    uni.showToast({ title: '订单ID无效', icon: 'none' })
    return
  }
  
  try {
    // 安全检查router.push是否存在
    if (router && typeof router.push === 'function') {
      router.push({
        path: '/pages/order-detail/detail',
        query: { id: orderId }
      })
    } else {
      // 降级方案：直接使用uni.navigateTo
      uni.navigateTo({
        url: `/pages/order-detail/detail?id=${orderId}`,
        fail: () => {
          uni.showToast({ title: '无法打开详情页', icon: 'none' })
        }
      })
    }
  } catch (e) {
    console.error('路由跳转失败:', e)
    // 降级方案：直接使用uni.navigateTo
    uni.navigateTo({
      url: `/pages/order-detail/detail?id=${orderId}`,
      fail: () => {
        uni.showToast({ title: '无法打开详情页', icon: 'none' })
      }
    })
  }
}

// 去支付
const goToPay = (orderId) => {
  if (!orderId) {
    uni.showToast({ title: '订单ID无效', icon: 'none' })
    return
  }
  
  try {
    // 安全检查router.push是否存在
    if (router && typeof router.push === 'function') {
      router.push({
        path: '/pages/order-payment/payment',
        query: { id: orderId }
      })
    } else {
      // 降级方案：直接使用uni.navigateTo
      uni.navigateTo({
        url: `/pages/order-payment/payment?id=${orderId}`,
        fail: () => {
          uni.showToast({ title: '无法打开支付页', icon: 'none' })
        }
      })
    }
  } catch (e) {
    console.error('路由跳转失败:', e)
    // 降级方案：直接使用uni.navigateTo
    uni.navigateTo({
      url: `/pages/order-payment/payment?id=${orderId}`,
      fail: () => {
        uni.showToast({ title: '无法打开支付页', icon: 'none' })
      }
    })
  }
}

// 退回大厅
const returnToHall = (orderId) => {
  uni.showModal({
    title: '确认退回',
    content: '确定要将此订单退回大厅吗？退回后您将不能再抢此订单',
    confirmText: '确认退回',
    cancelText: '取消',
    confirmColor: '#FF4D4F',
    success: (res) => {
      if (res.confirm) {
        // 模拟接口请求
        uni.showLoading({ title: '处理中...' })
        setTimeout(() => {
          const index = orders.value.findIndex(item => item.id === orderId)
          if (index > -1) {
            orders.value.splice(index, 1)
            uni.hideLoading()
            uni.showToast({ title: '已退回大厅', icon: 'success' })
          }
        }, 800)
      }
    }
  })
}

// 取消订单
const cancelOrder = async (orderId) => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消此订单吗？取消后将无法恢复',
    confirmText: '确认取消',
    cancelText: '再想想',
    confirmColor: '#FF4D4F',
    success: async (res) => {
      if (res.confirm) {
        // 调用真实接口请求
        uni.showLoading({ title: '取消中...' })
        try {
          const result = await cancelWorkOrderAPI(orderId)
          if (result.success) {
            // 更新订单状态
            const index = orders.value.findIndex(item => item.id === orderId)
            if (index > -1) {
              // 将订单移至已取消
              orders.value[index].tab = 'cancelled'
              orders.value[index].status = 3 // 已取消状态
              uni.showToast({ title: '订单已取消', icon: 'success' })
            }
          } else {
            uni.showToast({ title: result.message || '取消订单失败', icon: 'none' })
          }
        } catch (error) {
          console.error('取消订单失败:', error)
          uni.showToast({ title: '取消订单失败', icon: 'none' })
        } finally {
          uni.hideLoading()
        }
      }
    }
  })
}


// 页面加载时执行
onMounted(() => {
  // 验证路由实例是否有效
  if (!router) {
    console.warn('路由实例未初始化，已启用兼容模式')
  }
  // 获取工单数据
  fetchOrders()
})
</script>

<style scoped>
.orders-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  font-size: 28rpx;
}

.page-header {
  padding: 30rpx 30rpx 20rpx;
  background-color: rgba(255, 255, 255, 0.9);
  border-bottom: 1rpx solid #eee;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
}

.header-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.tabs-scroll {
  background-color: rgba(255, 255, 255, 0.9);
  padding: 15rpx 0;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(10rpx);
}

.tabs {
  display: flex;
  padding: 0 20rpx;
}

.tab-item {
  padding: 15rpx 30rpx;
  margin-right: 15rpx;
  background-color: #f5f7fa;
  border-radius: 40rpx;
  font-size: 26rpx;
  color: #666;
  position: relative;
  white-space: nowrap;
}

.tab-item.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.tab-badge {
  position: absolute;
  top: -5rpx;
  right: 15rpx;
  width: 30rpx;
  height: 30rpx;
  background-color: #ff4d4f;
  color: #fff;
  border-radius: 50%;
  font-size: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.order-list {
  padding: 20rpx;
}

.order-item {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 16rpx;
  padding: 25rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  padding-bottom: 15rpx;
  border-bottom: 1rpx dashed #eee;
}

.order-number {
  color: #333;
}

.number-label {
  color: #999;
  margin-right: 5rpx;
}

.order-status {
  padding: 5rpx 15rpx;
  border-radius: 40rpx;
  font-size: 24rpx;
  font-weight: 500;
}

.status-pending {
  background-color: #fff7e6;
  color: #ff9a2e;
}

.status-completed {
  background-color: #e6ffed;
  color: #00b42a;
}

.status-appointment {
  background-color: #e8f3ff;
  color: #1890ff;
}

.order-details {
  margin-bottom: 20rpx;
}

.detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
  line-height: 1.5;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-icon {
  margin-right: 15rpx;
  font-size: 28rpx;
  width: 30rpx;
  text-align: center;
}

.detail-label {
  color: #999;
  margin-right: 10rpx;
  width: 80rpx;
}

.detail-value {
  flex: 1;
  color: #666;
  word-break: break-all;
}

.price-row .detail-value {
  color: #ff4d4f;
  font-weight: 500;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15rpx;
  margin-top: 20rpx;
}

.detail-btn {
  padding: 0 25rpx;
  height: 60rpx;
  line-height: 60rpx;
  background-color: #f5f7fa;
  color: #666;
  border-radius: 30rpx;
  font-size: 24rpx;
}

.comment-btn {
  padding: 0 25rpx;
  height: 60rpx;
  line-height: 60rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border: none;
  border-radius: 30rpx;
  font-size: 24rpx;
}

.pay-btn {
  padding: 0 25rpx;
  height: 60rpx;
  line-height: 60rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border: none;
  border-radius: 30rpx;
  font-size: 24rpx;
}

.cancel-btn {
  padding: 0 25rpx;
  height: 60rpx;
  line-height: 60rpx;
  background-color: #ffffff;
  color: #ff4d4f;
  border: 1rpx solid #ff4d4f;
  border-radius: 30rpx;
  font-size: 24rpx;
}

.return-btn {
  padding: 0 25rpx;
  height: 60rpx;
  line-height: 60rpx;
  background-color: #fff2f0;
  color: #ff4d4f;
  border-radius: 30rpx;
  font-size: 24rpx;
}

.empty-state {
  padding: 100rpx 20rpx;
  text-align: center;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 16rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
}

.empty-icon {
  font-size: 80rpx;
  color: #667eea;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 30rpx;
  color: #666;
  margin-bottom: 15rpx;
  font-weight: 500;
}

.empty-subtext {
  font-size: 24rpx;
  color: #999;
}
</style>